<template>
  <div class="order-implement-record-dialog">
    <div class="order-implement-record">
      <div class="order-implement-record-sub">
        <div class="order-implement-record-sub-item">
          <span>客户名称：</span>
          <span>{{ data.companyName || "--" }}</span>
        </div>
        <div class="order-implement-record-sub-item">
          <span>项目编号：</span>
          <span>{{ data.code || "--" }}</span>
        </div>
        <div class="order-implement-record-sub-item">
          <span>项目经理：</span>
          <span>{{ userList.find(item => item.id == data.userId)?.name || "--" }}</span>
        </div>
      </div>
      <div class="order-implement-record-sub mb40">
        <div class="order-implement-record-sub-item">
          <span>计划发货：</span>
          <span>{{ formatHandler(data.planDeliveryTime) }}</span>
        </div>
        <div class="order-implement-record-sub-item">
          <span>实际发货：</span>
          <span>{{ formatHandler(data.deliveryTime) }}</span>
        </div>
        <div class="order-implement-record-sub-item">
          <span>计划调试：</span>
          <span>{{ formatHandler(data.planDebugCompletedTime[0]["name"]) }}</span>
        </div>
        <div class="order-implement-record-sub-item">
          <span>实际调试：</span>
          <span>{{ formatHandler(data.debugCompletedTime[0]["name"]) }}</span>
        </div>
        <div class="order-implement-record-sub-item">
          <span>计划验收：</span>
          <span>{{ formatHandler(data.planEndTime) }}</span>
        </div>
        <div class="order-implement-record-sub-item">
          <span>实际验收：</span>
          <span>{{ formatHandler(data.endTime) }}</span>
        </div>
      </div>
      <div class="mb30" v-for="item in listData" :key="item.id">
        <div class="tit">{{ item.name }}</div>
        <Table :columns="RECORD[item.code]['column']" :data="RECORD[item.code]['tableData']">
          <template #fileList>
            <TriggerContext
              class="trigger-context-status"
              type="dialog"
              :options="{
                title: '项目文档',
                width: '80vw',
                isShowFooter: false,
                slots: {
                  default: () => h(Document, { projectId: projectId, resourceButton })
                }
              }"
            >
              <div class="order-table-document">查看</div>
            </TriggerContext>
          </template>
          <template #[itm]="{ scope }" v-for="itm in timeColumnTemplateList" :key="itm">
            <AuthTable :permissions="resourceButton" key-string="implementRecord">
              <template #edit>
                <TriggerContext
                  :component="Calendar"
                  :props="{
                    'selected-Date': scope[itm],
                    handleDateChange: (date: any) => {
                      scope[itm] = date;
                    }
                  }"
                >
                  <div class="wik-column-rl">
                    <span class="order-table-name">{{ formatHandler(scope[itm]) }}</span>
                    <svg-icon name="rl"></svg-icon>
                  </div>
                </TriggerContext>
              </template>
              <template #get>
                <span class="order-table-text">{{ formatHandler(scope[itm]) }}</span>
              </template>
            </AuthTable>
          </template>
          <template #[itm]="{ scope }" v-for="itm in booleanList" :key="itm">
            <AuthTable :permissions="resourceButton" key-string="implementRecord">
              <template #edit>
                <TriggerContext
                  class="trigger-context-status"
                  :component="Status"
                  :props="{
                    id: scope[itm],
                    list: [
                      {
                        name: '是',
                        id: true
                      },
                      {
                        name: '否',
                        id: false
                      }
                    ],
                    handleDateChange: (date: any) => {
                      scope[itm] = date;
                    }
                  }"
                >
                  <div class="wik-column-rl">
                    <div class="order-table-status">
                      {{ formatBolHandler(scope[itm]) }}
                    </div>
                    <el-icon><ArrowDown /></el-icon>
                  </div>
                </TriggerContext>
              </template>
              <template #get>
                <span class="order-table-text">{{ formatBolHandler(scope[itm]) }}</span>
              </template>
            </AuthTable>
          </template>
          <template #[itm]="{ scope }" v-for="itm in dicSelectList" :key="itm">
            <AuthTable :permissions="resourceButton" key-string="implementRecord">
              <template #edit>
                <TriggerContext
                  class="trigger-context-status"
                  :component="Status"
                  :props="{
                    id: scope[itm],
                    list: getDict(DIC_LIST[itm]),
                    handleDateChange: (date: any) => {
                      console.log(scope, itm);
                      scope[itm] = date;
                    }
                  }"
                >
                  <div class="wik-column-rl">
                    <div class="order-table-status">
                      {{ getDictItem(DIC_LIST[itm], scope[itm]) }}
                    </div>
                    <el-icon><ArrowDown /></el-icon>
                  </div>
                </TriggerContext>
              </template>
              <template #get>
                <span class="order-table-text">{{ getDictItem(DIC_LIST[itm], scope[itm]) }}</span>
              </template>
            </AuthTable>
          </template>
          <template #[itm]="{ scope }" v-for="itm in otherInputHandler(RECORD[item.code]['column'])" :key="itm">
            <AuthTable :permissions="resourceButton" key-string="implementRecord">
              <template #edit>
                <div class="wik-column-rl">
                  <div class="order-table-status order-table-input">
                    <el-input v-model="scope[itm]"></el-input>
                  </div>
                  <el-icon><EditPen /></el-icon>
                </div>
              </template>
              <template #get>
                <span class="order-table-text">{{ scope[itm] }}</span>
              </template>
            </AuthTable>
          </template>
        </Table>
      </div>
    </div>
    <div class="wik-dialog-footer__default">
      <el-button type="default" @click="popClose">取消</el-button>
      <el-button type="primary" @click="save">确认</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import dayjs from "dayjs";
import { onMounted, ref, h, inject } from "vue";
import { ArrowDown, EditPen } from "@element-plus/icons-vue";
import Table from "@/components/Table/index.vue";
import TriggerContext from "@/components/TriggerContext/index.vue";
import AuthTable from "@/components/AuthTable/index.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElIcon, ElMessage } from "element-plus";
import { RECORD, DIC_LIST } from "../constant";
import { Calendar, Document, Status } from "./index";
import { getListAllUser } from "@/api/modules/sys";
import { useDict } from "@/hooks/useDict";
import { getTaskByProjectId, saveProjectTaskSave } from "@/api/modules/project";
const { getDictItem, getDict } = useDict(Object.values(DIC_LIST));
let userList = ref<any>([]);
const { data, projectId, resourceButton } = defineProps<{
  data: any;
  projectId: string;
  resourceButton: any;
}>();

const listData = ref<any>([]);

const popClose = inject<any>("popClose");
// 获取所有用户
const getListAllUserApi = async () => {
  const { data } = await getListAllUser();
  userList.value = data || [];
};
const formatHandler = (val: any) => {
  return val ? dayjs(val).format("YYYY年MM月DD日") : "--";
};
const formatBolHandler = (val: any) => {
  if (val == null || val == undefined || val === "") return "--";
  return val ? "是" : "否";
};
// 时间内容列
const timeColumnTemplateList = ref<any>(["planStartTime", "startTime", "planEndTime", "endTime"]);

// 是否内容列
const booleanList = ref<any>([
  "isEligibility",
  "isCover",
  "isSpeed",
  "isObstacleAvoidance",
  "isFluency",
  "isTds",
  "isStoreAll",
  "isTrafficAll",
  "isDirectives",
  "isChecked",
  "isLocation",
  "isCan",
  "isConfirmMainSize",
  "isConfirmMain",
  "isConfirm",
  "isNetwork",
  "isDocking",
  "isDCB",
  "isIo",
  "isRight",
  "isConnect",
  "isNormal",
  "isCustomize",
  "isNetworking",
  "isPrecision",
  "isChargeNormally",
  "isChargingMethod",
  "isFixed"
]);

// 字典选择项列
const dicSelectList = ref<any>(Object.keys(DIC_LIST));

const otherInputHandler = (list: any) => {
  const keys: any = list.map((item: any) => item.key);
  const otherKeys: any = [...timeColumnTemplateList.value, ...booleanList.value, ...dicSelectList.value, "fileList"];
  return keys.filter((item: any) => !otherKeys.includes(item));
};

const getTaskByProjectIdHandler = async () => {
  const { data } = await getTaskByProjectId({ projectId });
  listData.value = data || [];
  listData.value.forEach((item: any) => {
    RECORD[item.code]["tableData"] = [
      Object.assign({}, RECORD[item.code]["tableData"][0], (item.content && JSON.parse(item.content)) || {})
    ];
  });
};

const save = async () => {
  const data = JSON.parse(JSON.stringify(RECORD));

  const params = Object.keys(data).map((item: any) => {
    delete data[item].tableData[0]["tableColRef"];
    return data[item].tableData[0];
  });

  listData.value.forEach((item: any, index: number) => {
    item.planStartTime = params[index].planStartTime;
    item.startTime = params[index].startTime;
    item.planEndTime = params[index].planEndTime;
    item.endTime = params[index].endTime;
    item.content = JSON.stringify(params[index]);
  });

  await saveProjectTaskSave(listData.value);
  ElMessage.success("保存成功");
  getTaskByProjectIdHandler();
};

onMounted(async () => {
  getListAllUserApi();
  getTaskByProjectIdHandler();
});
</script>
<style lang="scss" scoped>
.order-implement-record-dialog {
  display: flex;
  flex-flow: column nowrap;
  position: relative;
  width: 100%;
  height: 85vh;
  padding: 20px;
  box-sizing: border-box;
  padding-bottom: 0;
  padding-right: 0;
}
.order-implement-record {
  flex: 1;
  overflow: auto;
  padding-right: 20px;
  &-sub {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 40px;
    margin-bottom: 20px;
    &-item {
      display: grid;
      grid-template-columns: 80px 1fr;
      gap: 10px;
      span {
        font-weight: 400;
        font-size: 14px;
      }
      span:first-child {
        color: #666666;
      }
      span:last-child {
        color: #333333;
      }
    }
  }
  .order-table-document {
    color: $primary-color;
  }
  .wik-column-rl {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: inherit;
    padding: 6px 10px;
    cursor: pointer;
    .order-table-status {
      flex: 1;
    }
    .order-table-input {
      height: 100%;
      margin-right: 10px;
      margin-left: 0;
    }
    svg {
      display: none;
      color: #aaaaaa;
      flex: 0 0 14px;
    }
    &:hover {
      svg {
        display: block;
      }
    }
  }
  .trigger-context {
    width: inherit;
    height: inherit;
  }
  .trigger-context-status {
    display: grid;
    align-items: center;
    width: 100%;
    height: inherit;
    cursor: pointer;
  }
  .tit {
    font-weight: 600;
    font-size: 16px;
    color: #333333;
    margin-bottom: 20px;
  }
  :deep(.el-input) {
    margin-right: 4px;
    .el-input__wrapper {
      box-shadow: none;
    }
  }
}
.wik-dialog {
  &-footer {
    &__default {
      flex: 0 0 50px;
      display: flex;
      justify-content: flex-end;
      background: #fff;
      z-index: 10000000;
      align-items: center;
      padding: 0 20px;
    }
  }
}
</style>
